package ntd.util.frame.javacv.ai_fuming;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.log.StaticLog;
import ntd.remote.file.ComRemoteFile;
import ntd.remote.file.bo.ComRemoteFileBO;
import ntd.remote.link.ComRegistryClient;
import ntd.sys.ToolJvm;
import ntd.tool.ToolCron;
import ntd.util.UtilCatch;
import ntd.util.frame.javacv.action.bean.AIServerDo;
import ntd.util.frame.javacv.config.AiConfig;
import ntd.util.frame.javacv.remote.AiVisionRemote;
import ntd.util.frame.javacv.tool.ToolFtpSync;
import ntd.util.fun.ComFun;
import ntd.util.util.ToolDuration;
import org.apache.commons.net.ftp.FTPFile;


import java.util.List;


import static ntd.util.frame.javacv.ComVisionApi.analysisRemoteList;
import static ntd.util.frame.javacv.ComVisionApi.initAiRemote;

public class AiClear {

    private static final List<String> paths = ListUtil.of(
            AiConfig.AI_RES_BASE_VIDEO_PATH_PERSON,
            AiConfig.AI_RES_BASE_IMG_PATH_PERSON,
            AiConfig.AI_RES_BASE_JSON_PATH_PERSON,
            AiConfig.AI_RES_BASE_CSV_PATH_PERSON,
            AiConfig.AI_RES_BASE_IMG_PATH_ALGAE,
            AiConfig.AI_RES_BASE_VIDEO_PATH_ALGAE,
            AiConfig.AI_RES_BASE_JSON_PATH_ALGAE,
            AiConfig.AI_RES_BASE_CSV_PATH_ALGAE,
            AiConfig.AI_RES_BASE_IMG_PATH_WATER,
            AiConfig.AI_RES_BASE_VIDEO_PATH_WATER,
            AiConfig.AI_RES_BASE_JSON_PATH_WATER,
            AiConfig.AI_RES_BASE_CSV_PATH_WATER
    );

    public static void main(String[] args) throws Exception {
        // AI 清理原始数据

        // 设置不允许退出
//        ToolJvm.setNoExit();
        //每天凌晨1点执行
//        CronUtil.schedule("0 0 2 * * ?", (Runnable) AiClear::start);
//
//        ToolCron.initTask();

        start();
    }

    public static void start() {
        // AI分析服务器文件清理
        // 预警结果超期文件及数据清理
        ToolDuration.duration(AiClear::clearAIServerFTPFile, "超期文件清理");
    }

    //清理ai服务器文件-新版本
    private static void clearAIServerTimeoutFile() {
        ThreadUtil.execAsync(() -> ComRegistryClient.run("client-code-" + RandomUtil.randomString(10), "客户端-测试删除Ai服务器超期文件", "61.52.247.249", 13021));

        DateTime date = DateUtil.date();
        DateTime dateBeforeThreeDay = DateUtil.offsetDay(date, -3);
        List<AiVisionRemote> aiVisionRemotes = initAiRemote();
        UtilCatch.tryCatchNoRes(() -> {
            for (AiVisionRemote aiVisionRemote : aiVisionRemotes) {
                connectAISever("D:/AI_result/ai/data",aiVisionRemote.aiServerDo,dateBeforeThreeDay);


                connectAISever("D:/AI_code/yolov5_henan/runs/detect/exp",aiVisionRemote.aiServerDo,dateBeforeThreeDay);





                // 生成结果清理
//            for (String path : paths) {
//                String resBasePath = "/" + path;
//                FTPFile[] resFiles = ftp.lsFiles(originBasePath);
//                for (FTPFile resFile : resFiles) {
//                    String name = resFile.getName();
//                    if (name.length() == 8 && DateUtil.compare(DateUtil.parse(name), dateBeforeThreeDay) < 0) {
//                        String resFilePath = StrUtil.format("{}/{}", resBasePath, name);
//                        ToolDuration.duration(() -> {
//                            ftp.delDir(resFilePath);
//                        }, StrUtil.format("清理机器视觉服务器[{}]超期结果文件夹[{}]", aiVisionRemote.aiServerDo.getUri(), path));
//                    }
//                }
//            }

                //清理模型结果生成的备份文件,14401971320-845619e095db4e7ea83c4f842cfb4835-20230413092541-WaterGarbage-image.jpg   13e560d403b34aa984044674672004fe-ai-online-analysis.jpeg
//                String resultBackupPath = "/D:/AI_code/yolov5_henan/runs/detect/exp";
//                FTPFile[] ftpBackUpFiles = ftp.lsFiles(resultBackupPath);
////                ftpBackUpFiles = Arrays.stream(ftpBackUpFiles).limit(150000).toArray(FTPFile[]::new);
//
//                for (FTPFile ftpFile : ftpBackUpFiles) {
//                    String name = ftpFile.getName();
//                    String[] split = name.split("-");
//                    if ((split.length > 3 && split[2].length() == 14 && DateUtil.compare(DateUtil.parse(split[2]), dateBeforeThreeDay) < 0)
//                            || StrUtil.contains(name,"ai-online-analysis")) {
//
//                        String path = StrUtil.format("{}/{}", resultBackupPath, ftpFile.getName());
//                        ToolDuration.duration(() -> {
//                            ftp.delFile(path);
//                        }, StrUtil.format("清理机器视觉服务器[{}]超期结果备份文件[{}]", aiVisionRemote.aiServerDo.getUri(), path));
//                    }
//                }
            }
        });

    }

    private static void connectAISever(String dirPath, AIServerDo aiServerDo, DateTime dateBeforeThreeDay){
//        String originBasePath = "D:/AI_result/ai/data";
        ComRemoteFileBO comRemoteFileBO = new ComRemoteFileBO();
        comRemoteFileBO.setRemoteCode(aiServerDo.getCode());
        comRemoteFileBO.setPath(dirPath);
        comRemoteFileBO.setDateTime(dateBeforeThreeDay);

        ToolDuration.duration(() -> {
            ComRemoteFile.me.del(comRemoteFileBO);
        }, StrUtil.format("清理机器视觉服务器[{}]超期原始文件夹[{}]", aiServerDo.getUri(), dirPath));
    }


    private static void clearAIServerFTPFile() {
        DateTime date = DateUtil.date();
        DateTime dateBeforeThreeDay = DateUtil.offsetDay(date, -3);
        List<AiVisionRemote> aiVisionRemotes = initAiRemote();
        UtilCatch.tryCatchNoRes(() -> {
            for (AiVisionRemote aiVisionRemote : aiVisionRemotes) {
                ToolFtpSync toolFtpSync = aiVisionRemote.getFtpSync();

                Ftp ftp = toolFtpSync.ftp();
                // 原始截图清理
                String originBasePath = "/ai/data";
                FTPFile[] ftpFiles = ftp.lsFiles(originBasePath);
//                ftpFiles = Arrays.stream(ftpFiles).limit(500).toArray(FTPFile[]::new);

                for (FTPFile ftpFile : ftpFiles) {
                    String name = ftpFile.getName();
                    String[] split = name.split("-");
                    if (split.length > 2 && split[1].length() == 8 && DateUtil.compare(DateUtil.parse(split[1]), dateBeforeThreeDay) < 0) {

                        String path = StrUtil.format("{}/{}", originBasePath, ftpFile.getName());
                        ToolDuration.duration(() -> {
                            ftp.delDir(path);
                        }, StrUtil.format("清理机器视觉服务器[{}]超期原始文件夹[{}]", aiVisionRemote.aiServerDo.getUri(), path));
                    }
                }

                // 生成结果清理
//            for (String path : paths) {
//                String resBasePath = "/" + path;
//                FTPFile[] resFiles = ftp.lsFiles(originBasePath);
//                for (FTPFile resFile : resFiles) {
//                    String name = resFile.getName();
//                    if (name.length() == 8 && DateUtil.compare(DateUtil.parse(name), dateBeforeThreeDay) < 0) {
//                        String resFilePath = StrUtil.format("{}/{}", resBasePath, name);
//                        ToolDuration.duration(() -> {
//                            ftp.delDir(resFilePath);
//                        }, StrUtil.format("清理机器视觉服务器[{}]超期结果文件夹[{}]", aiVisionRemote.aiServerDo.getUri(), path));
//                    }
//                }
//            }

                //清理模型结果生成的备份文件,14401971320-845619e095db4e7ea83c4f842cfb4835-20230413092541-WaterGarbage-image.jpg   13e560d403b34aa984044674672004fe-ai-online-analysis.jpeg
                String resultBackupPath = "/D:/AI_code/yolov5_henan/runs/detect/exp";
                FTPFile[] ftpBackUpFiles = ftp.lsFiles(resultBackupPath);
//                ftpBackUpFiles = Arrays.stream(ftpBackUpFiles).limit(150000).toArray(FTPFile[]::new);

                for (FTPFile ftpFile : ftpBackUpFiles) {
                    String name = ftpFile.getName();
                    String[] split = name.split("-");
                    if ((split.length > 3 && split[2].length() == 14 && DateUtil.compare(DateUtil.parse(split[2]), dateBeforeThreeDay) < 0)
                            || StrUtil.contains(name,"ai-online-analysis")) {

                        String path = StrUtil.format("{}/{}", resultBackupPath, ftpFile.getName());
                        ToolDuration.duration(() -> {
                            ftp.delFile(path);
                        }, StrUtil.format("清理机器视觉服务器[{}]超期结果备份文件[{}]", aiVisionRemote.aiServerDo.getUri(), path));
                    }
                }
            }
        });

    }
}
